<template>
    <view class="home-container" :style="[pageStyle, themeVars]">
        <!-- 头部组件 -->
        <cl-header title="首页" :left-show="false" :background-color="headerBgColor" :text-color="headerTextColor"></cl-header>

        <!-- 轮播图区域 -->
        <view class="banner-section">
            <u-swiper
                :list="bannerList"
                :autoplay="true"
                :circular="true"
                :interval="3000"
                :duration="500"
                height="160"
                radius="0"
                :indicator="true"
                indicator-pos="bottomCenter"
                :indicator-active-color="currentThemeConfig.accent"
                indicator-inactive-color="rgba(255, 255, 255, 0.3)"
                @click="handleBannerClick"
            >
                <template #default="{ item }">
                    <view class="banner-item">
                        <cl-image :src="item.image" width="100%" height="360rpx" mode="aspectFill" :lazy-load="true" :preview="false" />
                        <view class="banner-overlay">
                            <text class="banner-title">{{ item.title }}</text>
                        </view>
                    </view>
                </template>
            </u-swiper>
        </view>

        <!-- 功能卡片区域 -->
        <view class="features-section">
            <view class="features-grid">
                <view class="feature-card" :style="surfaceCardStyle" @click="navTo('pages/demo/index')">
                    <view class="card-icon">🧩</view>
                    <view class="card-content">
                        <text class="card-title" :style="textPrimaryStyle">组件演示</text>
                        <text class="card-description" :style="textSecondaryStyle">查看所有可用组件</text>
                    </view>
                </view>

                <view class="feature-card" :style="surfaceCardStyle" @click="navTo('pages/theme/index')">
                    <view class="card-icon">🔧</view>
                    <view class="card-content">
                        <text class="card-title" :style="textPrimaryStyle">更换主题</text>
                        <text class="card-description" :style="textSecondaryStyle">主题切换功能</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getBannerList } from '@/api/banner/index'
import { useTheme } from '@/composables/useTheme'
import { useThemeStyles } from '@/composables/useThemeStyles/index'
import { getImageUrl } from '@/utils'

// u-swiper需要的数据格式
interface USwiperItem {
    image: string
    title: string
    link_url?: string
}

// API返回的数据格式
interface BannerApiItem {
    id: number
    pic_path: string
    link_url?: string
    title: string
}

// 轮播图数据
const bannerList = ref<USwiperItem[]>([])

// 获取主题信息
const { currentThemeConfig, getThemeVars } = useTheme()
// 主题CSS变量（小程序/APP 端需要以内联方式提供）
const themeVars = computed(() => getThemeVars())
// 提取跨端样式（小程序也生效）
const { pageStyle, surfaceCardStyle, textPrimaryStyle, textSecondaryStyle, headerBgColor, headerTextColor } = useThemeStyles()

// 页面跳转
const navTo = (url: string) => {
    if (!url) return
    uni.navigateTo({ url: `/${url}` })
}

// 处理轮播图点击
const handleBannerClick = (item: USwiperItem) => {
    if (!item.link_url) return

    // 判断是否为外部链接
    if (item.link_url.startsWith('http')) {
        // #ifdef H5
        window.open(item.link_url, '_blank')
        // #endif
        // #ifdef MP-WEIXIN || APP-PLUS
        uni.showToast({
            title: '请在浏览器中打开',
            icon: 'none'
        })
        // #endif
    } else {
        // 内部页面跳转
        navTo(item.link_url)
    }
}

// 处理API数据转换为u-swiper格式
const transformBannerData = (apiData: BannerApiItem[]): USwiperItem[] => {
    return apiData.map((item) => ({
        image: getImageUrl(item.pic_path), // 拼接域名
        title: item.title,
        link_url: item.link_url
    }))
}

// 获取轮播图数据
const loadBannerData = async () => {
    try {
        const response = await getBannerList()
        if (response.code === 1 && response.data && response.data.length > 0) {
            bannerList.value = transformBannerData(response.data)
        } else {
            // 使用默认轮播图数据
            bannerList.value = getDefaultBanners()
        }
    } catch (error) {
        console.error('获取轮播图失败:', error)
        // 使用默认轮播图数据
        bannerList.value = getDefaultBanners()
    }
}

// 默认轮播图数据
const getDefaultBanners = (): USwiperItem[] => {
    return [
        {
            image: 'https://picsum.photos/750/360?random=1',
            title: '组件演示',
            link_url: 'pages/demo/index'
        },
        {
            image: 'https://picsum.photos/750/360?random=2',
            title: '主题实验室',
            link_url: 'pages/theme/index'
        }
    ]
}

// 页面加载时获取数据
onMounted(() => {
    loadBannerData()
})
</script>

<style lang="scss" scoped>
@import '@/styles/theme.scss';

.home-container {
    min-height: 100vh;
    background: var(--theme-background);
}

// 轮播图区域
.banner-section {
    margin-bottom: $spacing-lg;

    .banner-item {
        position: relative;
        width: 100%;
        height: 360rpx;
        overflow: hidden;

        .banner-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(transparent, rgba(0, 0, 0, 0.6));
            padding: $spacing-lg;

            .banner-title {
                color: white;
                font-size: $font-size-lg;
                font-weight: $font-weight-bold;
                text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.5);
            }
        }
    }
}

// 功能卡片区域
.features-section {
    padding: 0 $spacing-lg $spacing-xxl;

    .features-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280rpx, 1fr));
        gap: $spacing-md;

        .feature-card {
            background: var(--theme-surface);
            border: 1rpx solid var(--theme-border);
            border-radius: $border-radius-large;
            padding: $spacing-lg;
            text-align: center;
            transition: all 0.3s ease;
            backdrop-filter: blur(20rpx);

            &:active {
                transform: scale(0.98);
                opacity: 0.8;
            }

            .card-icon {
                font-size: 60rpx;
                margin-bottom: $spacing-md;
                display: block;
            }

            .card-content {
                .card-title {
                    display: block;
                    font-size: $font-size-lg;
                    color: var(--theme-text-primary);
                    font-weight: $font-weight-bold;
                    margin-bottom: $spacing-xs;
                }

                .card-description {
                    display: block;
                    font-size: $font-size-sm;
                    color: var(--theme-text-secondary);
                    line-height: 1.4;
                }
            }
        }
    }
}
</style>
